package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.Tree;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.TreeUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysTreeDictData;
import com.ruoyi.system.service.ISysTreeDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Aspect
@Component
@Slf4j
public class TreeAspect {

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.ruoyi.common.annotation.Tree)")
    public void treePointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "treePointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        // 获得注解
        Tree controllerTree = getAnnotationLog(joinPoint);
        if (controllerTree == null) {
            return;
        }

        List<SysTreeDictData> list = SpringUtils.getBean(ISysTreeDictDataService.class).selectListAll(new SysTreeDictData());
        new TreeUtils(Constants.TREE_DICT_KEY).buildTree(list);
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Tree getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Tree.class);
        }
        return null;
    }
}
